/**
 * @file command_executor_auto.cpp
 * @brief ESP32沙画机自动播放和恢复功能实现
 * 
 * 自动功能:
 * - 自动循环播放
 * - 自动暂停恢复
 * - 上下文感知命令处理
 * - 按键短按处理
 */

#include "command_executor.h"
#include "command_executor_debug.h"
#include "command_executor_performance.h"

// ==================== 自动循环播放实现 ====================

void CommandExecutor::setAutoPlayConfig(bool enabled, int displayTimeMinutes, bool useSweepMode) {
    autoPlayConfig.enabled = enabled;
    autoPlayConfig.displayTimeMs = displayTimeMinutes * 60 * 1000;
    autoPlayConfig.useSweepMode = useSweepMode;
    
    Serial.printf("[AUTOPLAY] 配置更新 - 启用: %s, 展示时间: %d分钟, 模式: %s\n", 
                  enabled ? "是" : "否", displayTimeMinutes, 
                  useSweepMode ? "扫图模式" : "普通模式");
}

CommandExecutor::AutoPlayConfig CommandExecutor::getAutoPlayConfig() const {
    return autoPlayConfig;
}

void CommandExecutor::updateAutoPlay() {
    if (!autoPlayConfig.enabled || !autoPlayWaiting) {
        return;
    }
    
    unsigned long currentTime = millis();
    if (currentTime - drawingCompletedTime >= autoPlayConfig.displayTimeMs) {
        autoPlayWaiting = false;
        
        // 直接使用常量字符串，避免String创建
        const char* nextCommand = autoPlayConfig.useSweepMode ? "sweepnext" : "next";
        Serial.printf("[AUTOPLAY] 自动播放触发: %s\n", nextCommand);
        
        if (autoPlayCommandCallback) {
            autoPlayCommandCallback(String(nextCommand));  // 只在回调时创建String
        }
    }
}

void CommandExecutor::stopAutoPlay() {
    if (autoPlayWaiting) {
        autoPlayWaiting = false;
        Serial.println("[AUTOPLAY] 自动播放已停止");
    }
}

void CommandExecutor::recordLastCommand(const String& command) {
    lastAutoPlayCommand = command;
}

void CommandExecutor::setAutoPlayCommandCallback(void (*callback)(const String&)) {
    autoPlayCommandCallback = callback;
}

// 统一的自动播放配置验证函数
bool CommandExecutor::validateAutoPlayParams(int minutes, const char* context) {
    if (minutes < 1 || minutes > 60) {
        Serial.printf("[ERROR] %s时间范围: 1-60分钟 (当前: %d)\n", context, minutes);
        return false;
    }
    return true;
}

int CommandExecutor::executeAutoPlayEnableCommand(bool enabled) {
    setAutoPlayConfig(enabled, autoPlayConfig.displayTimeMs / (60 * 1000), autoPlayConfig.useSweepMode);
    Serial.printf("[AUTOPLAY] 自动循环播放已%s\n", enabled ? "启用" : "禁用");
    return 0;
}

int CommandExecutor::executeAutoPlayTimeCommand(int minutes) {
    if (!validateAutoPlayParams(minutes, "自动播放")) {
        return 1;
    }
    
    setAutoPlayConfig(autoPlayConfig.enabled, minutes, autoPlayConfig.useSweepMode);
    Serial.printf("[AUTOPLAY] 展示时间已设置为 %d 分钟\n", minutes);
    return 0;
}

int CommandExecutor::executeAutoPlayModeCommand(bool useSweepMode) {
    setAutoPlayConfig(autoPlayConfig.enabled, autoPlayConfig.displayTimeMs / (60 * 1000), useSweepMode);
    Serial.printf("[AUTOPLAY] 播放模式已设置为 %s\n", useSweepMode ? "扫图模式" : "普通模式");
    return 0;
}

int CommandExecutor::executeAutoPlayStatusCommand() {
    Serial.println("[AUTOPLAY] === 自动循环播放状态 ===");
    Serial.printf("[AUTOPLAY] 启用状态: %s\n", autoPlayConfig.enabled ? "启用" : "禁用");
    Serial.printf("   展示时间: %d分钟\n", autoPlayConfig.displayTimeMs / (60 * 1000));
    Serial.printf("   播放模式: %s\n", autoPlayConfig.useSweepMode ? "扫图模式(sweepnext)" : "普通模式(next)");
    Serial.printf("   等待状态: %s\n", autoPlayWaiting ? "等待中" : "未等待");
    Serial.printf("   最后命令: %s\n", lastAutoPlayCommand.c_str());
    
    if (autoPlayWaiting) {
        unsigned long remainingTime = autoPlayConfig.displayTimeMs - (millis() - drawingCompletedTime);
        Serial.printf("   剩余时间: %lu秒\n", remainingTime / 1000);
    }
    
    return 0;
}

// ==================== 自动恢复实现 ====================

int CommandExecutor::executeAutoResumeEnableCommand() {
    setAutoResumeConfig(true, 60);
    Serial.println("[CMD] 自动恢复功能已启用（默认60秒后恢复）");
    return 0;
}

int CommandExecutor::executeAutoResumeStatusCommand() {
    Serial.println("=== 自动恢复状态 ===");
    Serial.printf("启用状态: %s\n", autoResumeConfig.enabled ? "启用" : "禁用");
    Serial.printf("延迟时间: %d秒\n", autoResumeConfig.delayMs / 1000);
    Serial.printf("等待状态: %s\n", autoResumeConfig.isWaitingForResume ? "等待中" : "未等待");
    
    if (autoResumeConfig.isWaitingForResume) {
        unsigned long currentTime = millis();
        unsigned long elapsedTime = currentTime - autoResumeConfig.pauseStartTime;
        unsigned long remainingTime = autoResumeConfig.delayMs - elapsedTime;
        Serial.printf("剩余时间: %lu秒\n", remainingTime / 1000);
    }
    
    return 0;
}

void CommandExecutor::setAutoResumeConfig(bool enabled, int delaySeconds) {
    autoResumeConfig.enabled = enabled;
    autoResumeConfig.delayMs = delaySeconds * 1000;
    autoResumeConfig.isWaitingForResume = false;
    
    Serial.printf("[AUTO_RESUME] 配置更新 - 启用: %s, 延迟: %d秒\n", 
                  enabled ? "是" : "否", delaySeconds);
}

CommandExecutor::AutoResumeConfig CommandExecutor::getAutoResumeConfig() const {
    return autoResumeConfig;
}

void CommandExecutor::updateAutoResume() {
    if (!autoResumeConfig.enabled || !autoResumeConfig.isWaitingForResume) {
        return;
    }
    
    unsigned long currentTime = millis();
    if (currentTime - autoResumeConfig.pauseStartTime >= autoResumeConfig.delayMs) {
        autoResumeConfig.isWaitingForResume = false;
        
        Serial.println("[AUTO_RESUME] 自动恢复触发，继续绘图");
        if (autoPlayCommandCallback) {
            autoPlayCommandCallback("start");
        }
    }
}

void CommandExecutor::startAutoResumeWait() {
    if (autoResumeConfig.enabled) {
        autoResumeConfig.isWaitingForResume = true;
        autoResumeConfig.pauseStartTime = millis();
        Serial.printf("[AUTO_RESUME] 开始等待自动恢复 (%d秒后)\n", autoResumeConfig.delayMs / 1000);
    }
}

void CommandExecutor::stopAutoResumeWait() {
    if (autoResumeConfig.isWaitingForResume) {
        autoResumeConfig.isWaitingForResume = false;
        Serial.println("[AUTO_RESUME] 停止自动恢复等待");
    }
}

bool CommandExecutor::isWaitingForAutoResume() const {
    return autoResumeConfig.isWaitingForResume;
}

// ==================== 上下文感知命令处理实现 ====================

int CommandExecutor::executeWithContext(const String& command) {
    // 🎯 简化版本：直接根据命令字符串执行，跳过复杂的解析和路由
    Serial.printf("🎯 执行命令: %s\n", command.c_str());
    
    // 直接字符串匹配，避免不必要的类型转换
    if (command == "sweepprep") return executeSweepAndPrepareCommand();
    if (command == "start") return executeStartCommand();
    if (command == "stop") return executeStopCommand();
    if (command == "pause") return executeStopCommand(); // 直接调用核心函数
    if (command == "home") return executeHomeCommand();
    if (command == "sweep") return executeSweepCommand();
    if (command == "sweepprev") return executeSweepPrevCommand();
    if (command == "sweepnext") return executeSweepNextCommand();
    if (command == "next") return executeNextCommand(); // 调用完整的next命令逻辑
    if (command == "prev") return executePrevCommand(); // 调用完整的prev命令逻辑
    
    // 其他命令仍使用原路径
    CommandType cmdType = parseCommandFast(command);
    return executeCommandByType(cmdType);
}

// 根据命令类型执行对应操作（减少字符串比较）
int CommandExecutor::executeCommandByType(CommandType cmdType) {
    switch (cmdType) {
        case CMD_START: return executeStartCommand();
        case CMD_STOP: return executeStopCommand();
        case CMD_PAUSE: return executeStopCommand(); // 直接调用核心函数
        case CMD_HOME: return executeHomeCommand();
        case CMD_SWEEP: return executeSweepCommand();
        case CMD_SWEEPPREP: return executeSweepAndPrepareCommand();
        case CMD_SWEEPPREV: return executeSweepPrevCommand();
        case CMD_SWEEPNEXT: return executeSweepNextCommand();
        case CMD_NEXT: return executeNextCommand(); // 调用完整的next命令逻辑
        case CMD_PREV: return executePrevCommand(); // 调用完整的prev命令逻辑
        case CMD_LIST: return executeListCommand();
        case CMD_STATUS: 
            Serial.println(executeStatusCommand()); 
            return 0;
        case CMD_INFO: 
            Serial.println(executeInfoCommand()); 
            return 0;
        case CMD_TASKINFO: return executeTaskInfoCommand();
        case CMD_COREINFO: return executeCoreInfoCommand();
        case CMD_POSITION: return executePositionCommand();
        case CMD_HELP: return executeHelpCommand();
        default:
            Serial.printf("❓ 未知命令类型: %d\n", cmdType);
            return 1;
    }
}

bool CommandExecutor::isDrawingCommand(const String& command) {
    return (command == "start" || command == "sweep" || 
            command.startsWith("sweep") || command == "home");
}

String CommandExecutor::getContinueCommandMapping(const String& lastCommand, const String& currentCommand) {
    if (lastCommand == currentCommand) {
        return "start"; // 相同命令时继续执行
    }
    return currentCommand; // 不同命令时执行新命令
}

// ==================== 按键处理实现 ====================

int CommandExecutor::executeShortPressStartStop() {
    if (*isDrawingActive) {
        Serial.println("[BUTTON] 短按 -> 停止绘图");
        return executeStopCommand();
    } else {
        Serial.println("[BUTTON] 短按 -> 开始绘图");
        
        // 如果没有图案，尝试加载默认图案
        if (!quickPatternCheck()) {
            int loadResult = loadDefaultOrLastPattern();
            if (loadResult != 0) {
                Serial.println("[BUTTON] 无可用图案，无法开始绘图");
                return loadResult;
            }
        }
        
        return executeStartCommand();
    }
}
